﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QQZiFramework
{
    public class JsonMessage
    {
        static readonly JsonMessage _default = new JsonMessage();
        public static JsonMessage Default { get { return _default; } }
        /// <summary>
        /// 错误消息
        /// </summary>
        public string Message { get; set; }
        public object Result { get; set; }

        /// <summary>
        /// 成功提示，空则显示默认消息（保存成功）
        /// </summary>
        public string Tip { get; set; }
        public string ToJson(bool ignoreNullValue = true, bool ignoreDefaultValue = true)
        {
            var jSetting = new JsonSerializerSettings { };
            if (ignoreDefaultValue) jSetting.DefaultValueHandling = DefaultValueHandling.Ignore;
            if (ignoreNullValue) jSetting.NullValueHandling = NullValueHandling.Ignore;

            jSetting.Formatting = Formatting.Indented;
            jSetting.MaxDepth = 10; //设置序列化的最大层数  
            string str = JsonConvert.SerializeObject(this, jSetting);
            str = str.Replace("-999999.0", "null").Replace("-999999", "null");
            return str;
        }
    }

    public class QJsonMessage : JsonMessage
    {
        [System.ComponentModel.DefaultValue(IDBEntity.DefaultNullValue)]
        public int Total { get; set; }
        public Dictionary<string, object> GroupBy { get; set; }
    }

    public class PaymentJsonMessage : JsonMessage
    {
        [System.ComponentModel.DefaultValue(IDBEntity.DefaultNullValue)]
        public int PayOrderId { get; set; }
    }

    public class QJsonMessage<T> : JsonMessage<T>
    {
        public int Total { get; set; }
    }

    public class JsonMessage<T>
    {
        /// <summary>
        /// 错误消息
        /// </summary>
        public string Message { get; set; }

        public T Result { get; set; }

        /// <summary>
        /// 成功提示，空则显示默认消息（保存成功）
        /// </summary>
        public string Tip { get; set; }
    }

    /// <summary>
    /// 客户端用来序列化服务器返回Result为字典的JsonMessage
    /// </summary>
    public class DicJsonResult : JsonMessage<Dictionary<string, string>>
    {

        /// <summary>
        /// 获取返回值中Result字典某项的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetResult(string key)
        {
            if (!Result.ContainsKey(key)) throw new Exception("返回结果Result不包含" + key);
            return Result[key];
        }
    }


}
